package zeebe.vertx;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.zeebe.client.ZeebeClient;
import io.zeebe.client.api.response.ActivatedJob;
import io.zeebe.client.api.worker.JobClient;
import io.zeebe.client.api.worker.JobHandler;

import java.util.Map;

public class VertxJobWorkerHandler implements JobHandler {
    ZeebeClient zeebeClient;

    public VertxJobWorkerHandler(ZeebeClient client) {
        this.zeebeClient = client;
    }

    @Override
    public void handle(JobClient jobClient, ActivatedJob activatedJob) throws Exception {
        System.out.println("开始执行jobWorker");
        Map<String, Object> map = activatedJob.getVariablesAsMap();
        String email = String.valueOf(map.get("email"));

        // 调用verification-code服务。启动verification-code,qcloud-email
        Vertx vertx = Vertx.vertx();
        WebClient webClient = WebClient.create(vertx, (new WebClientOptions()).setDefaultHost("192.168.99.152").setDefaultPort(30008));
        HttpRequest<Buffer> request = webClient.request(HttpMethod.POST, "/service/verification-code/v1/email/code");
        JsonObject input = new JsonObject().put("email", email);

        request.sendJsonObject(input, ar -> {

            if (ar.succeeded() && ar.result().statusCode() == 200) {
                System.out.println("服务调用成功");
                System.out.println(ar.result().bodyAsString());
                jobClient.newCompleteCommand(activatedJob.getKey()).send().join();

                //发送消息给消息捕获事件
                System.out.println("发送zeebe消息到捕获事件");
                zeebeClient.newPublishMessageCommand()
                        .messageName("verificate")
                        .correlationKey("2711992339@qq.com")
                        .send()
                        .join();
            } else {
                System.out.println("服务调用失败");
                System.out.println(ar.result().bodyAsString());
                jobClient.newFailCommand(activatedJob.getKey());
            }
            vertx.close();
        });
    }
}
